﻿using System;
using System.Collections.Generic;
using Dapper;
using zhangmenren.Db;
using zhangmenren.Models;

namespace zhangmenren.Repository
{
    public class EnterpriseRepository:BaseRepository
    {
        public int Add(EnterpriseEntity admin)
        {
            string sql = @"INSERT INTO Enterprise 
                            (Ico
                            ,Name
                            ,Present,CompanyAddress,Contacts,Tel,Area,Imgs,BrowseNum,HouseNum,Sort,State)
                        VALUES
                            (@Ico
                            ,@Name
                            ,@Present,@CompanyAddress,@Contacts,@Tel,@Area,@Imgs,@BrowseNum,@HouseNum,@Sort,@State)";
            return Execute(connection => connection.Execute(sql, admin));
        }

        public IEnumerable<EnterpriseEntity> Select()
        {
            string sql = @"SELECT Id,Name,Ico,Present,CompanyAddress,Contacts,Tel,State,Area,Imgs,(SELECT COUNT(Id) FROM QiYeShouChang WHERE QiYeShouChang.QiYeId=Enterprise.Id) AS HouseNum ,BrowseNum,Sort FROM Enterprise ORDER BY Sort DESC";
            return Execute(connection => connection.Query<EnterpriseEntity>(sql));
        }

        public IEnumerable<EnterpriseEntity> Select(int id)
        {
            string sql = @"SELECT Id,Name,Ico,Present,CompanyAddress,Contacts,Tel,Area,Imgs,BrowseNum,Sort,HouseNum FROM Enterprise WHERE Id=@Id";
            return Execute(connection => connection.Query<EnterpriseEntity>(sql,new{Id=id }));
        }

        /// <summary>
        /// 查找开启的企业名录
        /// </summary>
        /// <returns>The find.</returns>
        public IEnumerable<EnterpriseEntity> Find()
        {
            string sql = @"SELECT Id,Name,Ico,Present,CompanyAddress,Contacts,Tel,Area,Imgs,BrowseNum,Sort,HouseNum FROM Enterprise WHERE State=1";
            return Execute(connection => connection.Query<EnterpriseEntity>(sql));
        }

        public int Del(int id)
        {
            string sql = @"DELETE FROM Enterprise WHERE Id = @Id";
            return Execute(connection => connection.Execute(sql, new { Id = id }));
        }
        public int EditState(int id)
        {
            string sql = @"UPDATE Enterprise SET State = 1 WHERE Id = @Id";
            return Execute(connection => connection.Execute(sql, new { Id = id }));
        }

        public int EditSort(int id,int num)
        {
            string sql = @"UPDATE Enterprise SET Sort = @Sort WHERE Id = @Id";
            return Execute(connection => connection.Execute(sql, new { Id = id,Sort=num }));
        }

		public int AddLiuLan(int id)
		{
			string sql = @"UPDATE Enterprise SET BrowseNum = BrowseNum+1 WHERE Id = @Id";
			return Execute(connection => connection.Execute(sql, new { Id = id}));
		}

	}
}
